package com.jayqqaa12.robot.deprecated;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.jayqqaa12.jbase.util.L;
import com.jayqqaa12.jbase.util.Sec;

public class SinaLogin {

	public static WeiboUser login(String u, String p, HashMap<String, String> pastParams, String door) {

		WeiboUser user = new WeiboUser();
		DefaultHttpClient client = new DefaultHttpClient();

		try {
			// 获得rsaPubkey,rsakv,servertime等参数值
			HashMap<String, String> params = pastParams;
			if (params == null) params = preLogin(encodeAccount(u));

			System.out.println("get pre login params =" + params);

			HttpPost post = new HttpPost("http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.5)");
			post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");

			post.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
			post.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
			post.setHeader("Referer", "http://weibo.com/?c=spr_web_sq_firefox_weibo_t001");
			post.setHeader("Content-Type", "application/x-www-form-urlencoded");

			String nonce = makeNonce(6);

			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("encoding", "UTF-8"));
			nvps.add(new BasicNameValuePair("entry", "weibo"));
			nvps.add(new BasicNameValuePair("from", ""));
			nvps.add(new BasicNameValuePair("gateway", "1"));
			nvps.add(new BasicNameValuePair("nonce", nonce));
			nvps.add(new BasicNameValuePair("pagerefer", "http://i.firefoxchina.cn/old/"));
			nvps.add(new BasicNameValuePair("prelt", "111"));
			nvps.add(new BasicNameValuePair("pwencode", "rsa2"));
			nvps.add(new BasicNameValuePair("returntype", "META"));
			nvps.add(new BasicNameValuePair("rsakv", params.get("rsakv")));
			nvps.add(new BasicNameValuePair("savestate", "0"));
			nvps.add(new BasicNameValuePair("servertime", params.get("servertime")));

			nvps.add(new BasicNameValuePair("service", "miniblog"));

			// nvps.add(new BasicNameValuePair("sp", new
			// SinaSSOEncoder().encode(p, data, nonce)));
			nvps.add(new BasicNameValuePair("pcid", params.get("pcid")));

			if (door != null) nvps.add(new BasicNameValuePair("door", door));

			/******************** *加密密码 ***************************/
			ScriptEngineManager sem = new ScriptEngineManager();
			ScriptEngine se = sem.getEngineByName("javascript");
			// FileReader f = new FileReader("d://sso.js");
			se.eval(SinaSSOEncoder.getJs());
			String pass = "";

			if (se instanceof Invocable) {
				Invocable invoke = (Invocable) se;
				// 调用preprocess方法，并传入两个参数密码和验证码

				pass = invoke.invokeFunction("getpass", p, params.get("servertime"), nonce, params.get("pubkey"))
						.toString();

			}

			nvps.add(new BasicNameValuePair("sp", pass));
			nvps.add(new BasicNameValuePair("su", encodeAccount(u)));
			nvps.add(new BasicNameValuePair("url",
					"http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack"));

			nvps.add(new BasicNameValuePair("useticket", "1"));
			// nvps.add(new BasicNameValuePair("ssosimplelogin", "1"));
			nvps.add(new BasicNameValuePair("vsnf", "1"));

			post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

			HttpResponse response = client.execute(post);

			String entity = EntityUtils.toString(response.getEntity());

			System.out.println(entity);

			if (entity.replace("\"", "").indexOf("retcode=0") > -1) {

				String url = entity.substring(entity.indexOf("http://passport.weibo.com/wbsso/login?"),
						entity.indexOf("code=0") + 6);

				String strScr = ""; // 首页用户script形式数据
				String uid = ""; // 昵称

				// 获取到实际url进行连接
				HttpGet getMethod = new HttpGet(url);
				response = client.execute(getMethod);
				entity = EntityUtils.toString(response.getEntity());
				System.out.println(entity);

				Document doc = Jsoup.parse(entity);

				uid = entity.substring(entity.indexOf("uniqueid") + 11, entity.lastIndexOf("userid") - 3).trim();

				// url = entity.substring(entity.indexOf("userdomain") + 13,
				// entity.lastIndexOf("\""));
				// getMethod = new HttpGet("http://weibo.com/" + url);
				// response = client.execute(getMethod);
				// entity = EntityUtils.toString(response.getEntity());
				// Elements els = doc.select("script");
				//
				// // System.out.println(entity);
				// if (els != null && els.size() > 0) {
				// for (int i = 0, leg = els.size(); i < leg; i++) {
				//
				// if (els.get(i).html().indexOf("$CONFIG") > -1) {
				// strScr = els.get(i).html();
				// break;
				// }
				// }
				// }
				//
				// if (!strScr.equals("")) {
				// ScriptEngineManager manager = new ScriptEngineManager();
				// ScriptEngine engine = manager.getEngineByName("javascript");
				//
				// engine.eval("function getMsg(){" + strScr +
				// "return $CONFIG['onick'];}");
				// if (engine instanceof Invocable) {
				// Invocable invoke = (Invocable) engine;
				// // 调用preprocess方法，并传入两个参数密码和验证码
				// // nick = invoke.invokeFunction("getMsg",
				// // null).toString();
				// }
				// }

				user.setUserName(u);
				user.setUserPass(p);
				user.setUid(uid);
				user.setCookies(client.getCookieStore().getCookies());

				L.i("登录成功  id=" + uid);
			} else if ((entity.replace("\"", "").indexOf("retcode=4049") > -1)) {
				L.i("需要输入验证码了");

				params.put("checkImg", checkImg(params.get("pcid")));
				user.setParam(params);

			} else if ((entity.replace("\"", "").indexOf("retcode=2070") > -1)) {
				L.i("验证码 error");
				params.put("checkImg", checkImg(params.get("pcid")));
				user.setParam(params);

			} else {
				L.i("其他问题 密码错误等");
				user = null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
			// logger.info(e.getMessage());
			user = null;
		}

		return user;
	}

	/**
	 * 根据URL,get网页
	 * 
	 * @param url
	 * @throws IOException
	 */
	private static String get(String url, DefaultHttpClient client) throws IOException {
		HttpGet get = new HttpGet(url);
		HttpResponse response = client.execute(get);
		System.out.println(response.getStatusLine());
		HttpEntity entity = response.getEntity();
		String result = dump(entity);
		get.abort();
		return result;
	}

	/**
	 * 新浪微博预登录，获取密码加密公钥
	 * 
	 * @param unameBase64
	 * @return 返回从结果获取的参数的哈希表
	 * @throws IOException
	 */
	private static HashMap<String, String> preLogin(String unameBase64) throws IOException {
		DefaultHttpClient client = new DefaultHttpClient();

		String url = "http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=&rsakt=mod&client=ssologin.js(v1.4.5)&_="
				+ "_=" + new Date().getTime();
		return getParaFromResult(get(url, client));
	}

	/**
	 * 从新浪返回的结果字符串中获得参数
	 * 
	 * @param result
	 * @return
	 */
	private static HashMap<String, String> getParaFromResult(String result) {
		HashMap<String, String> hm = new HashMap<String, String>();
		result = result.substring(result.indexOf("{") + 1, result.indexOf("}"));
		String[] r = result.split(",");
		String[] temp;
		for (int i = 0; i < r.length; i++) {
			temp = r[i].split(":");
			for (int j = 0; j < 2; j++) {
				if (temp[j].contains("\"")) temp[j] = temp[j].substring(1, temp[j].length() - 1);
			}
			hm.put(temp[0], temp[1]);
		}
		return hm;
	}

	/**
	 * 打印页面
	 * 
	 * @param entity
	 * @throws IOException
	 */
	private static String dump(HttpEntity entity) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "utf8"));
		return IOUtils.toString(br);
	}

	private static String encodeAccount(String account) {
		String userName = "";
		try {
			userName = Base64.encodeBase64String(URLEncoder.encode(account, "UTF-8").getBytes());
			// userName =
			// BASE64Encoder.encode(URLEncoder.encode(account,"UTF-8").getBytes());
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return userName;
	}

	private static String makeNonce(int len) {
		String x = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		String str = "";
		for (int i = 0; i < len; i++) {
			str += x.charAt((int) (Math.ceil(Math.random() * 1000000) % x.length()));
		}
		return str;
	}

	public static String checkImg(String pcid) {
		String url = "http://login.sina.com.cn/cgi/pin.php?r=" + (long) (Math.random() * 100000000) + "&s=0&p=" + pcid;

		Map<String, String> headers = new HashMap<String, String>();

		headers.put("Accept", "text/html, application/xhtml+xml, */*");
		headers.put("Referer", "http://weibo.com/");
		headers.put("Accept-Language", "zh-cn");
		headers.put("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN");
		headers.put("Host", "login.sina.com.cn");
		headers.put("Connection", "Keep-Alive");
		headers.put("Cache-Control", "no-cache");
		headers.put("Cookie", null);

		HttpResponse response = HttpUtils.doGet(url, headers);
		byte[] img = null;
		InputStream in = HttpUtils.getInputStreamFromResponse(response);
		
		try {
			img = new byte[1024];
			in.read(img);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return "data:image/png;base64,"+ Base64.encodeBase64String(img);

	}

	private static String getServerTime() {
		// long servertime = new Date().getTime() / 1000;
		// return String.valueOf(servertime);

		return String.valueOf(System.currentTimeMillis() / 1000);
	}

	public static void main(String[] args) {
		
		


	}

}
